// 表单管理

// 切换材料项
function toggleMaterial(header) {
    const content = header.nextElementSibling;
    const isActive = header.classList.contains('active');

    // 关闭其他项
    document.querySelectorAll('.material-header.active').forEach(h => {
        if (h !== header) {
            h.classList.remove('active');
            h.nextElementSibling.classList.remove('show');
        }
    });

    // 切换当前项
    header.classList.toggle('active');
    content.classList.toggle('show');
}

// 创建材料项
function createMaterialItem(title, index) {
    return `
        <div class="material-item">
            <div class="material-header" onclick="toggleMaterial(this)">
                <span class="material-number">${index}</span>
                <span class="material-title">${title}</span>
                <span class="toggle-icon">▼</span>
            </div>
            <div class="material-content">
                <textarea class="material-desc" data-section="${title}" placeholder="请输入${title}相关信息..."></textarea>
                <div class="upload-area" onclick="document.getElementById('file-${index}').click()">
                    <input type="file" id="file-${index}" class="file-input" multiple 
                           accept="image/jpeg,image/jpg,image/png,application/pdf" 
                           onchange="handleFileUpload(this, '${title}')">
                    <div>📎 点击上传文件</div>
                    <div style="font-size:12px;color:#999;margin-top:5px">支持 JPG、PNG、PDF</div>
                </div>
                <div class="file-preview" id="preview-${index}"></div>
            </div>
        </div>
    `;
}

// 初始化材料列表
function initMaterials() {
    const container = document.getElementById('materialsList');
    container.innerHTML = MATERIAL_SECTIONS.map((title, i) =>
        createMaterialItem(title, i + 1)
    ).join('');
}

// 获取表单数据
function getFormData() {
    const data = {
        basicInfo: {
            deliveryName: document.getElementById('deliveryName').value.trim(),
            thirdPartyName: document.getElementById('thirdPartyName').value.trim(),
            caseType: document.getElementById('caseType').value,
            caseDate: document.getElementById('caseDate').value,
            closeDate: document.getElementById('closeDate').value,
            city: document.getElementById('city').value.trim(),
            caseHandler: document.getElementById('caseHandler').value.trim(),
            caseDesc: document.getElementById('caseDesc').value.trim()
        },
        materials: []
    };

    MATERIAL_SECTIONS.forEach(title => {
        const desc = document.querySelector(`textarea[data-section="${title}"]`);
        data.materials.push({
            title: title,
            description: desc ? desc.value.trim() : '',
            files: window.fileStorage[title] || []
        });
    });

    return data;
}

// 验证表单
function validateForm() {
    const { deliveryName, caseType, caseDate, city, caseHandler, caseDesc } = getFormData().basicInfo;

    if (!deliveryName) {
        showMessage('请输入闪送员姓名', 'error');
        return false;
    }
    if (!caseType) {
        showMessage('请选择案件类型', 'error');
        return false;
    }
    if (!caseDate) {
        showMessage('请选择发案日期', 'error');
        return false;
    }
    if (!city) {
        showMessage('请输入所属城市', 'error');
        return false;
    }
    if (!caseHandler) {
        showMessage('请输入案件责任人', 'error');
        return false;
    }
    if (!caseDesc) {
        showMessage('请输入案件描述', 'error');
        return false;
    }

    return true;
}

// 保存数据
function saveData() {
    const data = getFormData();
    localStorage.setItem('caseData', JSON.stringify(data));
    showMessage('数据已保存', 'success');
}

// 加载数据
function loadData() {
    const saved = localStorage.getItem('caseData');
    if (!saved) return;

    const data = JSON.parse(saved);

    // 恢复基本信息
    if (data.basicInfo) {
        document.getElementById('deliveryName').value = data.basicInfo.deliveryName || '';
        document.getElementById('thirdPartyName').value = data.basicInfo.thirdPartyName || '';
        document.getElementById('caseType').value = data.basicInfo.caseType || '';
        document.getElementById('caseDate').value = data.basicInfo.caseDate || '';
        document.getElementById('closeDate').value = data.basicInfo.closeDate || '';
        document.getElementById('city').value = data.basicInfo.city || '';
        document.getElementById('caseHandler').value = data.basicInfo.caseHandler || '';
        document.getElementById('caseDesc').value = data.basicInfo.caseDesc || '';
    }

    // 恢复描述
    if (data.materials) {
        data.materials.forEach(m => {
            const desc = document.querySelector(`textarea[data-section="${m.title}"]`);
            if (desc) desc.value = m.description || '';
        });
    }
}